home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3226 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can a function return a (pointer to a) function?
  5. Date: 27 Jan 1996 02:56:12 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4ec48c$kij@castle.nando.net>
  8. References: <4ebaaa$jh6@barnacle.iol.ie>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: vyger513.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4ebaaa$jh6@barnacle.iol.ie>,
  14. "John D. Hourihane" <hourihaj@iol.ie> writes:
  15.  
  16. >I am trying to write a function which will return a pointer to a function,
  17. >but I'm having no luck.
  18. >
  19. >The toy program below illustrates (I hope) what I want to be able to do,
  20. >but as it stands it won't compile for me. The idea is that the call to
  21. >'(pick(ADD))' will return a pointer to the 'add' function which is then
  22. >dereferenced and used.
  23. >
  24. >But like I say, it doesn't compile. It complains 'Declaration terminated
  25. >incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
  26. >
  27. >Any reply, posted here or by email, would be great.
  28. >
  29. >/* The toy program, to use a function that returns a
  30. > * pointer to a function.
  31. > */
  32. >
  33. >#include <stdio.h>
  34. >
  35. >#define ADD            0
  36. >#define MULTIPLY    1
  37. >
  38. >int add(int x, int y);
  39. >int multiply(int x, int y);
  40. >
  41. >/* pick returns a pointer to a function which will operate on two integers */
  42. >(int f(int, int)) *pick(int s);
  43.  
  44. Replace above with:
  45.  
  46.     int (*pick(int))(int, int);
  47.  
  48. >
  49. >int main()
  50. >{
  51. >    printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
  52. >    printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
  53. >    return 0;
  54. >}
  55. >
  56. >int add(int x, int y)
  57. >{    return x + y; }
  58. >
  59. >int multiply(int x, int y)
  60. >{    return x * y; }
  61. >
  62. >(int f(int, int)) *pick(int s)
  63.  
  64. And replace the above line with:
  65.  
  66.     int (*pick(int s))(int, int)
  67.  
  68. >{    if (s == ADD)
  69. >        return add;
  70. >    return multiply;
  71. >}
  72.  
  73. Bill McCarthy
  74. actuary@nando.net
  75. Wendell, NC  USA
  76.  
  77.